package com.efrei.uchat.client.gui.control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Set;

import javax.swing.JPanel;

import com.efrei.uchat.client.gui.view.CroomTab;
import com.efrei.uchat.client.model.Croom;
import com.efrei.uchat.client.model.Message;

public class CroomTabControl extends TabControl implements ActionListener {

	private Croom croom;
	private CroomTab tab;
	
	private UChatListModel<String> usersModel = new UChatListModel<String>();
	private UChatListModel<Message> messagesModel = new UChatListModel<Message>();

	public CroomTabControl(UChatControl context, Croom croom) {
		super(context);
		this.croom = croom;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		CroomTab tab = (CroomTab) getTab();
		if(e.getSource()==tab.getBtnLeave()) {
			// leave croom
			getContext().leaveCroom(croom.getTopic());
		} else if(e.getSource()==tab.getBtnSubmit()
				|| e.getSource()==tab.getTextMessage()) {
			// send message by pressing Submit/press enter in jtextfield
			String text;
			if((text = tab.getTextMessage().getText().trim()).length()!=0) {
				getContext().sendMessage(
						croom.getTopic(),
						text);
				tab.getTextMessage().setText("");
			}
		}
	}

	@Override
	public void update() {
		//TODO: update users and messages
	}
	
	public void setUsers(Set<String> users) {
		usersModel.clear();
		for (String user : users) {
			usersModel.addElement(user);
		}
	}
	
	public void addMessage(Message message) {
		messagesModel.addElement(message);
	}
	
	@Override
	public void setTab(JPanel tab) {
		this.tab = (CroomTab) tab;
		this.tab.getBtnLeave().addActionListener(this);
		this.tab.getBtnSubmit().addActionListener(this);
		this.tab.getTextMessage().addActionListener(this);
		// users
		this.tab.getListUsers().setModel(usersModel);
		// messages
		this.tab.getListMessages().setModel(messagesModel);
	}
	
	public Croom getCroom() {
		return croom;
	}
	
	public void setCroom(Croom croom) {
		this.croom = croom;
	}

	@Override
	public JPanel getTab() {
		return tab;
	}
	
	public UChatListModel<String> getUsersModel() {
		return usersModel;
	}
	
	public UChatListModel<Message> getMessagesModel() {
		return messagesModel;
	}
}
